package ru.marketsoft.reminder.tools;

import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;

/**
 * User: dimka3210
 * Date: 14.03.13
 * Time: 21:51
 */
public class Settings {
    private static Settings ourInstance = new Settings();
    private HashMap<String, String> settingsMap = new HashMap<String, String>();
    private File stg = new File("stg.ini");
    private FileInputStream fileInputStream;
    private FileOutputStream fileOutputStream;
    private Properties properties = new Properties();

    public static Settings getInstance() {
        return ourInstance;
    }

    private Settings() {
        try {
            String filePath = stg.getAbsolutePath();
            fileInputStream = new FileInputStream(filePath);
            properties.load(fileInputStream);
            Enumeration enumeration = properties.keys();
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement().toString();
                settingsMap.put(key, properties.getProperty(key));
            }

            fileOutputStream = new FileOutputStream(filePath);
            properties.store(fileOutputStream, "no comment");
            fileInputStream.close();
            fileOutputStream.close();
        } catch (FileNotFoundException fnfexp) {
            try {
                new File("stg.ini").createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setProperty(String _key, String _value) {
        try {
            String filePath = stg.getAbsolutePath();
            fileInputStream = new FileInputStream(filePath);
            properties.load(fileInputStream);
            Enumeration enumeration = properties.keys();
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement().toString();
                settingsMap.put(key, properties.getProperty(key));
            }
            settingsMap.put(_key, _value);
            properties.setProperty(_key, _value);
            fileOutputStream = new FileOutputStream(filePath);
            properties.store(fileOutputStream, "no comment");
            fileInputStream.close();
            fileOutputStream.close();
        } catch (FileNotFoundException fnfexp) {
            try {
                new File("stg.ini").createNewFile();
                Settings.getInstance().setProperty(_key, _value);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getProperty(String _key){
        return settingsMap.get(_key);
    }
}
